package com.hupu.jrs.ui.messagelist

import com.hupu.jrs.api.forum.ForumApi
import com.hupu.jrs.bean.Message
import com.hupu.jrs.injector.PerActivity
import com.hupu.jrs.otto.MessageReadEvent
import com.hupu.jrs.util.ToastUtil
import com.squareup.otto.Bus
import java.util.ArrayList
import javax.inject.Inject
import rx.Subscription
import rx.android.schedulers.AndroidSchedulers
import rx.functions.Action1
import rx.functions.Func1

/**
 * Created by sll on 2016/3/11.
 */
@PerActivity
class MessageListPresenter @Inject
constructor(private val mForumApi: ForumApi, private val mBus: Bus) : MessageListContract.Presenter {

    private var mSubscription: Subscription? = null
    private var mMessageListView: MessageListContract.View? = null
    private var lastTid = ""
    private var page = 1

    private val messages = ArrayList<Message>()

    override fun onMessageListReceive() {
        mMessageListView!!.showLoading()
        loadMessageList(true)
    }

    private fun loadMessageList(clear: Boolean) {
        mSubscription = mForumApi.getMessageList(lastTid, page)
                .observeOn(AndroidSchedulers.mainThread())
                .doOnNext(Action1<Any> {
                    if (clear) {
                        messages.clear()
                    }
                })
                .map(Func1<Any, List<Any>> { messageData ->
                    if (messageData != null && messageData.status === 200) {
                        addMessages(messageData.result.list)
                    } else null
                })
                .subscribe(Action1<List<Any>> { messages ->
                    if (messages != null) {
                        if (messages.isEmpty()) {
                            mMessageListView!!.onEmpty()
                        } else {
                            mMessageListView!!.hideLoading()
                            mMessageListView!!.onRefreshCompleted()
                            mMessageListView!!.onLoadCompleted(true)
                            mMessageListView!!.renderMessageList(messages)
                        }
                    } else {
                        loadError()
                    }
                }, Action1<Throwable> { loadError() })
    }

    private fun loadError() {
        if (messages.isEmpty()) {
            mMessageListView!!.onError()
        } else {
            ToastUtil.showToast("数据加载失败，请重试")
            mMessageListView!!.hideLoading()
            mMessageListView!!.onRefreshCompleted()
            mMessageListView!!.onLoadCompleted(true)
        }
    }

    private fun addMessages(threadList: List<Message>): List<Message> {
        for (thread in threadList) {
            if (!contains(thread)) {
                messages.add(thread)
            }
        }
        if (!messages.isEmpty()) {
            lastTid = messages[messages.size - 1].tid
        }
        return messages
    }

    private operator fun contains(message: Message): Boolean {
        var isContain = false
        for (message1 in messages) {
            if (message.tid.equals(message1.tid)) {
                isContain = true
                break
            }
        }
        return isContain
    }

    override fun onRefresh() {
        lastTid = ""
        page = 1
        onMessageListReceive()
    }

    override fun onReload() {

    }

    override fun onLoadMore() {
        page++
        loadMessageList(false)
    }

    override fun onMessageClick(message: Message) {
        mMessageListView!!.showContentUi(message.tid, message.pid, Integer.valueOf(message.page))
        mForumApi.delMessage(message.id).subscribe(Action1<Any> { baseData ->
            if (baseData != null && baseData.status === 200) {
                mMessageListView!!.removeMessage(message)
                mBus.post(MessageReadEvent())
            }
        }, Action1<Throwable> { })
    }

    fun attachView(view: MessageListContract.View) {
        mMessageListView = view
    }

    fun detachView() {
        if (mSubscription != null && !mSubscription!!.isUnsubscribed) {
            mSubscription!!.unsubscribe()
        }
        mMessageListView = null
    }
}
